package com.to8to.autotask.sendmsg;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.autotask.util.DBUtil;
import com.to8to.commons.utils.StringUtil;
import com.to8to.es.util.LogUtil;
import com.to8to.msgcenter.thrift.SendMsgRequest;
import com.to8to.msgcenter.thrift.TTarget;

/**
 * @author Tom.zhang
 *
 */
public class SendMsgTask implements Runnable {

	private static final Logger logger = LoggerFactory
			.getLogger(SendMsgTask.class);

	@Override
	public void run() {

		String msg = choiceMsg();

		if (msg == null || msg.isEmpty()) {
			logger.info("没有找到发送内容.....操作结束");
			return;
		}

		SendMsgRequest req = new SendMsgRequest();
		String bizdata = "{\"ns\":\"scheduleBatchSendMsg\"}";
		req.setBizdata(bizdata);
		req.setContent(msg);

		boolean isSendTestPhone = false;

		/****************************************************************************************/
		/** 测试代码 （2月10为测试效果） */
		boolean useTestPhone = false;
		List<String> testPhones = null;
		List<Integer> day_month = getDayAndMonth();
		if (day_month != null) {
			if (day_month.get(0) == 10 && day_month.get(1) == 1) {
				useTestPhone = true;
				testPhones = new ArrayList<String>();
				testPhones.add("18703635730");
				testPhones.add("13751874259");
				testPhones.add(MsgConstants.TEST_PHONE_1);
				testPhones.add(MsgConstants.TEST_PHONE_2);
				testPhones.add(MsgConstants.TEST_PHONE_3);
			}
		}
		/****************************************************************************************/

		/** 分批发送的次数 */

		logger.info("开始分批群发短信.......发送内容：{}", msg);
		List<String> canSell_phones = null;
		if (useTestPhone) {
			canSell_phones = testPhones;
		} else {
			canSell_phones = selectPhoneBySql(MsgConstants.SQL_CANSELL);
		}

		/** 如果不是为2月11 */
		if (day_month.get(0) != 11 || day_month.get(1) != 1) {

			if (canSell_phones != null && !canSell_phones.isEmpty()) {
				/** 可售 */
				sendMsg(req, canSell_phones, isSendTestPhone);
				isSendTestPhone = true;
				logger.info(
						"延期时间在12月15号00：00-3月16号00：00的延期可售项目 短信发送结束.......已发送 {} 条 短信",
						canSell_phones.size());
			}
			/** 如果为测试日期,则不用走下面的代码 */
			if (useTestPhone) {
				return;
			}

			List<String> delay_phones = selectPhoneBySql(MsgConstants.SQL_HAS_DELAYTIME);
			if (delay_phones != null && !delay_phones.isEmpty()) {
				/** 延期可售 */
				sendMsg(req, delay_phones, isSendTestPhone);
				isSendTestPhone = true;
				logger.info(
						"12月15号后发布，当前属于非结束状态且分配公司大于0的已售项目(有延期时间） 短信发送结束.......已发送 {} 条 短信",
						delay_phones.size());
			}

		}

		List<String> selled_phones = selectPhoneBySql(MsgConstants.SQL_SELLED);
		if (selled_phones != null && !selled_phones.isEmpty()) {
			/** 已售 */
			sendMsg(req, selled_phones, isSendTestPhone);
			isSendTestPhone = true;
			logger.info("12月15号后发布，分配公司为0的已售项目 短信发送结束.......已发送 {} 条 短信",
					selled_phones.size());
		}

		logger.info("群发短信结束.......");

	}

	/**
	 * 群发短信
	 * 
	 * @param req
	 *            群发对象
	 * @param phones
	 *            群发手机号
	 */
	private void sendMsg(SendMsgRequest req, List<String> phones,
			boolean isSendTestPhone) {
		int times = getSendTimes(phones.size());
		for (int time = 0; time < times; time++) {

			List<String> subPhones = getSubPhoneTarget(time, times, phones);
			List<TTarget> targets = packListTarget(subPhones);
			if (targets == null || targets.isEmpty()) {
				break;
			}

			// 第一次没有发送测试号码的情况下
			if (time == 0 && !isSendTestPhone) {
				targets.addAll(MsgConstants.getTestPhone());
			}

			req.setTargets(targets);
			try {
				BeanUtil.getMsgCenterService().sendMsgManDao(req);
				logger.info("第 {} 批群发短信结束.......已发送 {} 条 短信", time + 1,
						targets.size());
			} catch (Exception e) {
				logger.error("群发短信失败！ 异常：{}", LogUtil.logStackTrace(e));
			}
			try {
				Thread.sleep(TimeUnit.MINUTES.toMillis(15));
			} catch (InterruptedException e) {
				logger.error("线程异常！ {}", LogUtil.logStackTrace(e));
			}
		}
	}

	/**
	 * @param time
	 *            第几个子集合
	 * @param times
	 *            共有多少个子集合
	 * @param phones
	 *            集合
	 * @return 子集合
	 */
	public List<String> getSubPhoneTarget(int time, int times,
			List<String> phones) {
		List<String> subPhones = new ArrayList<String>();
		int start = time * MsgConstants.BATCH_SEND_SIZE;
		if (time == times - 1) {
			subPhones = phones.subList(start, phones.size());
		} else {
			subPhones = phones.subList(start, start
					+ MsgConstants.BATCH_SEND_SIZE);
		}
		return subPhones;
	}

	public int getSendTimes(long size) {
		int times = (int) (size / MsgConstants.BATCH_SEND_SIZE);
		return size % MsgConstants.BATCH_SEND_SIZE == 0 ? times : times + 1;
	}

	/**
	 * @return 根据时间获取发送的内容
	 */
	private String choiceMsg() {

		String msg = null;
		List<Integer> day_month = getDayAndMonth();
		int day = day_month.get(0);
		int month = day_month.get(1) + 1;

		if (day == 11 && month == 2) {
			msg = MsgConstants.MSG_2_11;
		} else if (day == 16 && month == 2) {
			msg = MsgConstants.MSG_2_16;
		} else if (day == 24 && month == 2) {
			msg = MsgConstants.MSG_2_24;
		} else if (day == 1 && month == 3) {
			msg = MsgConstants.MSG_3_1;
		} else if (day == 10 && month == 2) {
			msg = MsgConstants.MSG_2_16;
		}
		return msg;
	}

	/**
	 * @param phones
	 * @return 封装发送对象
	 */
	public List<TTarget> packListTarget(List<String> phones) {

		if (phones != null && !phones.isEmpty()) {
			List<TTarget> targets = new ArrayList<TTarget>();
			for (String phone : phones) {
				TTarget target = new TTarget();
				target.setContact(phone);
				target.setSend_type(1);
				targets.add(target);
			}
			return targets;
		}

		return null;
	}

	public List<String> selectPhoneBySql(String querySql) {

		Connection connect = null;
		ResultSet result = null;
		PreparedStatement stat = null;

		try {
			connect = DBUtil.getConnection();

			List<String> phoneList = new ArrayList<String>();
			stat = connect.prepareStatement(querySql);
			result = stat.executeQuery();
			while (result.next()) {
				String phone = result.getString("phone");
				if (StringUtil.isEmpty(phone))
					continue;
				phoneList.add(phone);
			}

			return phoneList;

		} catch (Throwable e) {
			logger.error("查询失败", e, LogUtil.logStackTrace(e));
			return null;
		} finally {
			DBUtil.releaseSource(result, stat, connect);
		}
	}

	/**
	 * @return 几号 几月
	 */
	public static List<Integer> getDayAndMonth() {
		Date date = new Date();
		@SuppressWarnings("deprecation")
		List<Integer> day_month = Arrays
				.asList(date.getDate(), date.getMonth());
		return day_month;
	}

	public static void main(String[] args) throws Exception {
		// Date date = new Date();
		// // 今天是几号
		// int day = date.getDate();
		// int day2 = date.getDay();
		// int month = date.getMonth();
		// System.out.println(day + "  " + day2);
		// System.out.println(month);
		//
		// List<Integer> ssss = Arrays.asList(1, 2, 3, 43, 546, 63, 5, 56, 4);
		// System.out.println(ssss.subList(0, 20));
		// System.out.println(ssss);

		Thread thread = new Thread(new SendMsgTask());
		thread.start();

		// SendMsgRequest req = new SendMsgRequest();
		// String bizdata = "{\"ns\":\"定时批量发送短信\"}";
		// req.setBizdata(bizdata);
		// req.setContent("你好吗。。。。啊啊啊啊啊啊");
		// List<TTarget> tt = MsgConstants.getTestPhone();
		// req.setTargets(tt);
		// BeanUtil.getMsgCenterService().sendMsg(req);

		// System.out.println(MsgConstants.getTestPhone());

	}
}
